#!/usr/bin/env php
<?php
// -----------------------------------------------------------------------------
// sdefastsearch - A PHP Fast ESP Search API
// Copyright (C) 2008,2009 sueddeutsche.de GmbH, Hultschiner Str. 8, D-81677 München
// www.sueddeutsche.de.de - Andreas.Scheerer@sueddeutsche.de
//
// This file is part of sdefastsearch.
//
// sdefastsearch is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------

/**
 * Cli example showing how te free memory after performing search.
 * 
 * @author  Andreas Scheerer <Andreas.Scheerer@sueddeutsche.de
 * @version $Id$ 
 */

//--------------------------------------------------------------------------
//---                               config                               ---
//-------------------------------------------------------------------------- 
set_include_path(dirname(__FILE__).'/../../src/');

//--------------------------------------------------------------------------
//---                               includes                             ---
//-------------------------------------------------------------------------- 
require_once 'sde/fastsearch/SearchFactory.php';
include_once 'sde/fastsearch/query/Query.php';

//--------------------------------------------------------------------------
//---                                 main                               ---
//-------------------------------------------------------------------------- 

// Params
// remove script name
array_shift($argv);
if (count($argv) < 2) {
    showInfo();
    exit();
}

$host     = $argv[0];
$port     = $argv[1];
$query    = "";
$viewName = "";

if (count($argv) > 2)
   $viewName = $argv[2];

// Properties
$properties = array (
    'fastsearch.SearchFactory' => "http.HttpSearchFactory",
    'fastsearch.http.qservers' => "$host:$port",
    /*
    'fastsearch.http.usecurl'  => true,
    'fastsearch.http.curloptions' => array(
        CURLOPT_PROXY => 'localhost',
        CURLOPT_PROXYPORT => 10000,
        CURLOPT_PROXYTYPE => CURLPROXY_SOCKS5)
    */
);

try {
    // Get search factory
    $searchFactory = SearchFactory::newInstance($properties);

    // Printing list of views.
    if (empty($viewName)) {
        $list = $searchFactory->getSearchViewList();
    
        print "Views located at $host:$port\n";
    
        if (count($list) > 0) {
            for ($i = 0; $i < count($list); $i++) 
                print $list[$i]."\n";
        } else {
            print "No views found.\n";
        }
        exit();
    }

    // Get view.
    $view = $searchFactory->getSearchView($viewName);
    
    // Check given search string count
    if (count($argv) < 4) {
        print "No search strings given. Nothing to be done here. Bye, bye!\n";
        exit;
    } else {
        print "Executing search for ".(count($argv)-3)." query string(s)... \n\n";
    }
    
    // Do a search for every search string given
    for ($i = 3; $i < count($argv); $i++) {
       
        $query    = $argv[$i];
        $queryNum = $i-2; 
    
        $query = str_replace('"', '\"', $query);
        $query = 'string("'.trim($query).'", mode=simpleall)';
        
        $theQuery = new Query();
        $theQuery->setQueryString($query);
    
        print "--- Query no. $queryNum ---\n";
        print "Query string: " . $theQuery->getQueryString() . "\n";
        $memUsage['pre'] = round(memory_get_usage()/1024);
        $result = $view->search($theQuery);
        $memUsage['post'] = round(memory_get_usage()/1024);
        print "Matching documents: ".$result->getDocCount()."\n";
        
        $result->prepareUnset();
        unset($result);
        $memUsage['unset'] = round(memory_get_usage()/1024);

        print "Allocated Memory before executing query .......... ".$memUsage['pre']." kb\n";
        print "Allocated Memory after executing query ........... ".$memUsage['post']." kb\n";
        print "Allocated Memory after unset of query result ..... ".$memUsage['unset']." kb\n\n";
    }
    
    // Exit
    print "Search execution complete.\n";

} catch (ConfigurationException $e) {
    print "CONFIG_ERROR: ".$e->getMessage()."\n\nException trace:\n";
    print $e->getTraceAsString();
    exit(1);
} catch (Exception $e) {
    print "ERROR: ".$e->getMessage()."\n\nException trace:\n";
    print $e->getTraceAsString();
    exit(1);
}


//--------------------------------------------------------------------------
//---                             functions                              ---
//-------------------------------------------------------------------------- 
function showInfo() {
    print "usage: freeMemorySearch.php <host> <port> [view] [one or more query terms]\n";
    print "If no view and query terms are given, a list of avaible views will be shown.\n";
    print "example: freeMemorySearch.php localhost 15100 myview George Washington\n";
}
